<?php
/******************************
 * EQdkp
 * Copyright 2002-2003
 * Licensed under the GNU GPL.  See COPYING for full terms.
 * ------------------
 * addtrigger.php
 * Began: November 2007
 *
 *
 ******************************/

define('EQDKP_INC', true);
define('IN_ADMIN', true);
$eqdkp_root_path = './../';
include_once($eqdkp_root_path . 'common.php');

class Add_Trigger extends EQdkp_Admin
{
    var $trigger     = array();            // Holds item data if URI_ITEM is set               @var trigger 
    var $old_trigger = array();            // Holds item data from before POST                 @var old_trigger
    
    function add_trigger()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $eqdkp_root_path, $SID;
        
        parent::eqdkp_admin();
        
        $this->trigger = array(
            'select_trigger_name' => post_or_db('select_trigger_name'),
            'trigger_name'        => post_or_db('trigger_name'),
            'trigger_holders'     => post_or_db('trigger_holders'),
	    'trigger_date'	  => post_or_db('trigger_date'),
            'raid_gained_id'      => post_or_db('raid_gained_id')
        );
        
        // Vars used to confirm deletion
        $this->set_vars(array(
            'confirm_text'  => $user->lang['confirm_delete_item'],
            'uri_parameter' => URI_ITEM)
        );
        
        $this->assoc_buttons(array(
            'add' => array(
                'name'    => 'add',
                'process' => 'process_add',
                'check'   => 'a_item_add'),
            'update' => array(
                'name'    => 'update',
                'process' => 'process_update',
                'check'   => 'a_item_upd'),
            'delete' => array(
                'name'    => 'delete',
                'process' => 'process_delete',
                'check'   => 'a_item_del'),
            'form' => array(
                'name'    => '',
                'process' => 'display_form',
                'check'   => 'a_item_'))
        );
        
        // Build the item array
        // ---------------------------------------------------------
        if ( $this->url_id )
        {
	    $sql = 'SELECT trigger_name, trigger_holder, raid_gained_id, trigger_date, trigger_group_key
		    FROM ' . TRIGGERS_TABLE . "
		    WHERE trigger_id='" . $this->url_id . "'";

            $result = $db->query($sql);
            if ( !$row = $db->fetch_record($result) )
            {
                message_die($user->lang['error_invalid_item_provided']);
            }
            $db->free_result($result);
        
            $this->trigger = $row['trigger_date'];
            $this->trigger = array(
                'select_trigger_name' => post_or_db('select_trigger_name'),
                'trigger_name'        => post_or_db('trigger_name',  $row),
		'trigger_date'	      => post_or_db('trigger_date', $row),
                'raid_gained_id'          => post_or_db('raid_gained_id',    $row)
            );
        
            $holders = array();
            $sql = 'SELECT trigger_holder
                    FROM ' . TRIGGERS_TABLE . "
                    WHERE trigger_group_key='" . $row['trigger_group_key'] . "'";
            $result = $db->query($sql);
            while ( $row = $db->fetch_record($result) )
            {
                $holders[] = $row['trigger_holder'];
            }
            $this->trigger['trigger_holders'] = ( !empty($_POST['trigger_holders']) ) ? $_POST['trigger_holders'] : $holders;
            unset($holders);
        }
    }
    
    function error_check()
    {
        global $user;
        
        if ( (!isset($_POST['trigger_holders'])) || (!is_array($_POST['trigger_holders'])) )
        {
            $this->fv->errors['trigger_holders'] = $user->lang['fv_required_buyers'];
        }
        $this->fv->is_filled(array(
            'raid_gained_id'    => $user->lang['fv_required_raidid'])
        );
    
        if ( !empty($_POST['trigger_name']) )
        {
            $this->trigger['trigger_name'] = $_POST['trigger_name'];
        }
        elseif ( !empty($_POST['select_trigger_name']) )
        {
            $this->trigger['trigger_name'] = $_POST['select_trigger_name'];
        }
        else
        {
            $this->fv->errors['trigger_name'] = $user->lang['fv_required_item_name'];
        }
        
        return $this->fv->is_error();
    }
    
    // ---------------------------------------------------------
    // Process Add
    // ---------------------------------------------------------
    function process_add()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $eqdkp_root_path, $SID;
        
        // Get item name from the appropriate field
        $this->trigger['trigger_name'] = ( !empty($_POST['trigger_name']) ) ? $_POST['trigger_name'] : $_POST['select_trigger_name'];
        
        // Find out the item's date based on the raid it's associated with
        $this->time = $db->query_first('SELECT raid_date FROM ' . RAIDS_TABLE . " WHERE raid_id='" . $_POST['raid_gained_id'] . "'");
        
        //
        // Generate our group key
        //
        $group_key = $this->gen_group_key($this->trigger['trigger_name'], $this->time, $_POST['raid_gained_id']);
        
        //
        // Add item to selected members
        //
        $this->add_new_trigger($group_key);
        
        //
        // Logging
        //
	$trigger_holders = implode(', ', $_POST['trigger_holders']);
        $log_action = array(
            'header'       => '{L_ACTION_ITEM_ADDED}',
            '{L_NAME}'     => $this->trigger['trigger_name'],
            '{L_BUYERS}'   => $trigger_holders,
            '{L_RAID_ID}'  => $_POST['raid_gained_id'],
            '{L_ADDED_BY}' => $this->admin_user);
        $this->log_insert(array(
            'log_type'   => $log_action['header'],
            'log_action' => $log_action)
        );
        
        //
        // Success message
        //
        $success_message = sprintf($user->lang['admin_add_trigger_success'], $this->trigger['trigger_name'], $trigger_holders);
        $link_list = array(
            'Add Trigger'   => 'addtrigger.php' . $SID,
            'List Triggers' => 'listtriggers.php' . $SID);
        $this->admin_die($success_message, $link_list);
    }
    
    // ---------------------------------------------------------
    // Process Update
    // ---------------------------------------------------------
    function process_update()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $eqdkp_root_path, $SID;
        
        //
        // Remove the old trigger
        //
        $this->remove_old_trigger();
        
        // Get item name from the appropriate field
        $this->trigger['trigger_name'] = ( !empty($_POST['trigger_name']) ) ? $_POST['trigger_name'] : $_POST['select_trigger_name'];
        
        // Find out the item's date based on the raid it's associated with
        $this->time = $db->query_first('SELECT raid_date FROM ' . RAIDS_TABLE . " WHERE raid_id='" . $_POST['raid_gained_id'] . "'");
        
        //
        // Generate our group key
        //
        $group_key = $this->gen_group_key($this->trigger['trigger_name'], $this->time, $_POST['raid_gained_id']);
        
        //
        // Add item to selected members
        //
        $this->add_new_trigger($group_key);
        
        //
        // Logging
        //
	$trigger_holders = implode(', ', $_POST['trigger_holders']);
        $log_action = array(
            'header'             => '{L_ACTION_ITEM_UPDATED}',
            '{L_NAME_BEFORE}'    => $this->old_trigger['trigger_name'],
            '{L_BUYERS_BEFORE}'  => implode(', ', $this->old_trigger['trigger_holders']),
            '{L_RAID_ID_BEFORE}' => $this->old_trigger['raid_gained_id'],
            '{L_NAME_AFTER}'     => $this->find_difference($this->old_trigger['trigger_name'], $this->trigger['trigger_name']),
            '{L_BUYERS_AFTER}'   => implode(', ', $this->find_difference($this->old_trigger['trigger_holders'], $_POST['trigger_holders'])),
            '{L_RAID_ID_AFTER}'  => $this->find_difference($this->old_trigger['raid_gained_id'], $_POST['raid_gained_id']),
            '{L_UPDATED_BY}'     => $this->admin_user);
        $this->log_insert(array(
            'log_type'   => $log_action['header'],
            'log_action' => $log_action)
        );
        
        //
        // Success message
        //
        $success_message = sprintf($user->lang['admin_update_trigger_success'], $this->old_trigger['trigger_name'], implode(', ', $this->old_trigger['trigger_holders']));
        $link_list = array(
            'Add Trigger'   => 'addtrigger.php' . $SID,
            'List Triggers' => 'listtriggers.php' . $SID);
        $this->admin_die($success_message, $link_list);
    }
    
    // ---------------------------------------------------------
    // Process Delete (confirmed)
    // ---------------------------------------------------------
    function process_confirm()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $eqdkp_root_path, $SID;
        
        //
        // Remove the old item
        //
        $this->remove_old_trigger();
        
        //
        // Logging
        //
	$trigger_holders = implode(', ', $this->old_trigger['trigger_holders']);
        $log_action = array(
            'header'      => '{L_ACTION_ITEM_DELETED}',
            '{L_NAME}'    => $this->old_trigger['trigger_name'],
            '{L_BUYERS}'  => $trigger_holders,
            '{L_RAID_ID}' => $this->old_trigger['raid_gained_id']);
        $this->log_insert(array(
            'log_type'   => $log_action['header'],
            'log_action' => $log_action)
        );
        
        //
        // Success message
        //
        $success_message = sprintf($user->lang['admin_delete_trigger_success'], $this->old_trigger['trigger_name'], $trigger_holders);
        $link_list = array(
            'Add Trigger'   => 'addtrigger.php' . $SID,
            'List Triggers' => 'listtriggers.php' . $SID);
        $this->admin_die($success_message, $link_list);
    }
    
    // ---------------------------------------------------------
    // Process helper methods
    // ---------------------------------------------------------
    function remove_old_trigger()
    {
        global $db;
    
	$trigger_ids  = array();
        $old_holders  = array();
        
        //
        // Build the trigger_ids, old_holders and old_trigger arrays
        //
        $sql = 'SELECT i2.*
                FROM (' . TRIGGERS_TABLE . ' i1
                LEFT JOIN ' . TRIGGERS_TABLE . " i2
                ON i1.trigger_group_key = i2.trigger_group_key)
                WHERE i1.trigger_id='" . $this->url_id . "'";
        $result = $db->query($sql);
        while ( $row = $db->fetch_record($result) )
        {
            $trigger_ids[] = $row['trigger_id'];

            $old_holders[] = addslashes($row['trigger_holder']);
            $this->old_trigger = array(
                'trigger_name'   => addslashes($row['trigger_name']),
                'trigger_holders' => $old_holders,
                'raid_gained_id'     => addslashes($row['raid_gained_id']),
                'trigger_date'   => addslashes($row['trigger_date'])
            );
        }
        
        //
        // Remove the trigger entry from the triggers table
        //
        $sql = 'DELETE FROM ' . TRIGGERS_TABLE . '
                WHERE trigger_id IN (' . implode(', ', $trigger_ids) . ')';
        $db->query($sql);
        
    }
    
    function add_new_trigger($group_key)
    {
        global $db;
        
        $query = array();
        
        foreach ( $_POST['trigger_holders'] as $member_name )
        {
            $query[] = $db->build_query('INSERT', array(
                'trigger_name'      => stripslashes($this->trigger['trigger_name']),
                'trigger_holder'     => $member_name,
                'raid_gained_id'        => $_POST['raid_gained_id'],
                'trigger_date'      => $this->time,
                'trigger_group_key' => $group_key,
                'trigger_added_by'  => $this->admin_user)
            );
        }
        
        //
        // Add trigger(s) to triggers table
        //
        // Remove the field names from our built queries
        foreach ( $query as $key => $sql )
        {
            $query[$key] = preg_replace('#^.+\) VALUES (\(.+\))#', '\1', $sql);
        }
        
        $sql = 'INSERT INTO ' . TRIGGERS_TABLE . '
                (trigger_name, trigger_holder, raid_gained_id, trigger_date, trigger_group_key, trigger_added_by)
                VALUES ' . implode(', ', $query);
        $db->query($sql);

    }
    
    // ---------------------------------------------------------
    // Display form
    // ---------------------------------------------------------
    function display_form()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $eqdkp_root_path, $SID;
        
        //
        // Build member and holder drop-downs
        //
	$holder_source = ( $this->url_id ) ? $this->trigger['trigger_holders'] : (( isset($_POST['trigger_holders']) ) ? $_POST['trigger_holders'] : '');
        
        $sql = 'SELECT member_name
                FROM ' . MEMBERS_TABLE . '
                ORDER BY member_name';
        $result = $db->query($sql);
        while ( $row = $db->fetch_record($result) )
        {
            $tpl->assign_block_vars('members_row', array(
                'VALUE'  => $row['member_name'],
                'OPTION' => $row['member_name'])
            );
            
            if ( @in_array($row['member_name'], $holder_source) )
            {
                $tpl->assign_block_vars('holders_row', array(
                    'VALUE'  => $row['member_name'],
                    'OPTION' => $row['member_name'])
                );
            }
        }
        $db->free_result($result);

        //
        // Build raid drop-down
        //
        // Show all raids?
        $show_all = ( (!empty($_GET['show'])) && ($_GET['show'] == 'all') ) ? true : false;
        
        // Make two_weeks two weeks before the date the item was purchased
	if ($this->trigger['trigger_date'])
	{
		$two_weeks = mktime(0, 0, 0, date('m', $this->trigger['trigger_date']), date('d', $this->trigger['trigger_date'])-14, date('y', $this->trigger['trigger_date']));
	}
	else
	{
        	$two_weeks = mktime(0, 0, 0, date('m', $this->time), date('d', $this->time)-14, date('y', $this->time));
	}

        $sql_where_clause = ( $show_all ) ? '' : ' WHERE (raid_date >= ' . $two_weeks . ')';
        $sql = 'SELECT raid_id, raid_name, raid_date
                FROM ' . RAIDS_TABLE .
                $sql_where_clause . '
                ORDER BY raid_date DESC';

        $result = $db->query($sql);
        $raid_id = ( isset($_GET['raid_id']) ) ? $_GET['raid_id'] : '0'; // 'Add items from this raid' link
        while ( $row = $db->fetch_record($result) )
        {
            $tpl->assign_block_vars('raids_row', array(
                'VALUE'    => $row['raid_id'],
                'SELECTED' => ( ($raid_id == $row['raid_id']) || ($this->trigger['raid_gained_id'] == $row['raid_id']) ) ? ' selected="selected"' : '',
                'OPTION'   => date($user->style['date_notime_short'], $row['raid_date']) . ' - ' . stripslashes($row['raid_name']))
            );
        }
        $db->free_result($result);

        //
        // Build trigger drop-down
        //
        $previous_trigger = '';
	$sql = 'SELECT DISTINCT trigger_name
		FROM ' . TRIGGERS_TABLE . '
		ORDER BY trigger_name DESC';	
        $result = $db->query($sql);
        while ( $row = $db->fetch_record($result) )
        {
            $trigger_select_name = stripslashes(trim($row['trigger_name']));
            $trigger_name        = stripslashes(trim($this->trigger['trigger_name']));

            if ( $previous_trigger != $trigger_select_name )
            {
                $tpl->assign_block_vars('triggers_row', array(
                    'VALUE'    => $trigger_select_name,
                    'SELECTED' => ( ($trigger_select_name == $trigger_name) || ($trigger_select_name == $this->trigger['select_trigger_name']) ) ? ' selected="selected"' : '',
                      // 'OPTION'   => '(' . sprintf($format, $row['item_value']) . ') - ' . $item_select_name)
		     'OPTION'   => $trigger_select_name  )

                );
                
                $previous_trigger = $trigger_select_name;
            }
        }
        $db->free_result($result);

        $tpl->assign_vars(array(
            // Form vars
            'F_ADD_TRIGGER'        => 'addtrigger.php' . $SID,
            'TRIGGER_ID'           => $this->url_id,
            'U_ADD_RAID'        => 'addraid.php'.$SID,
            'S_MULTIPLE_HOLDERS' => ( !$this->url_id ) ? true : false,

            // Form values
            'TRIGGER_NAME'  => stripslashes($this->trigger['trigger_name']),

            // Language
            'L_ADD_TRIGGER_TITLE'      => $user->lang['addtrigger_title'],
            'L_HOLDERS'              => $user->lang['holders'],
            'L_HOLD_CTRL_NOTE'      => '('.$user->lang['hold_ctrl_note'].')<br />',
            'L_SEARCH_MEMBERS'      => $user->lang['search_members'],
            'L_RAID'                => $user->lang['raid'],
            'L_ADD_RAID'            => strtolower($user->lang['add_raid']),
            'L_NOTE'                => $user->lang['note'],
            'L_ADDITEM_RAIDID_NOTE' => ( !$show_all ) ? sprintf($user->lang['additem_raidid_note'], '<a href="addtrigger.php'.$SID.'&amp;show=all'.(( $this->url_id ) ? '&amp;' . URI_ITEM . '=' . $this->url_id : '').'">')
                                       : $user->lang['additem_raidid_showall_note'],
            'L_TRIGGER'                => $user->lang['trigger'],
            'L_SEARCH'              => strtolower($user->lang['search']),
            'L_SEARCH_EXISTING'     => $user->lang['search_existing'],
            'L_SELECT_EXISTING'     => $user->lang['select_existing'],
            'L_OR'                  => strtolower($user->lang['or']),
            'L_ENTER_NEW'           => $user->lang['enter_new'],
            'L_ADD_TRIGGER'            => $user->lang['add_trigger'],
            'L_RESET'               => $user->lang['reset'],
            'L_UPDATE_TRIGGER'         => $user->lang['update_trigger'],
            'L_DELETE_TRIGGER'         => $user->lang['delete_trigger'],

            // Form validation
            'FV_TRIGGER_HOLDERS' => $this->fv->generate_error('trigger_holders'),
            'FV_RAID_ID'     => $this->fv->generate_error('raid_id'),
            'FV_TRIGGER_NAME'   => $this->fv->generate_error('trigger_name'),

            // Javascript messages
            'MSG_NAME_EMPTY'    => $user->lang['fv_required_trigger_name'],
            'MSG_RAID_ID_EMPTY' => $user->lang['fv_required_raidid'],

            // Buttons
            'S_ADD' => ( !$this->url_id ) ? true : false)
        );
        
        $eqdkp->set_vars(array(
            'page_title'    => sprintf($user->lang['admin_title_prefix'], $eqdkp->config['guildtag'], $eqdkp->config['dkp_name']).': '.$user->lang['addtrigger_title'],
            'template_file' => 'admin/addtrigger.html',
            'display'       => true)
        );
    }
}

class Trigger_Search extends EQdkp_Admin
{
    function trigger_search()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $SID;
        
        parent::eqdkp_admin();
        
        $this->assoc_buttons(array(
            'search' => array(
                'name'    => 'search',
                'process' => 'process_search',
                'check'   => 'a_item_'),
            'form' => array(
                'name'    => '',
                'process' => 'display_form',
                'check'   => 'a_item_'))
        );
    }
    
    function error_check()
    {
        $this->fv->is_filled('query');
        if ( strlen($_POST['query']) < 2 )
        {
            $this->fv->errors['query'] = '';
        }
        
        return $this->fv->is_error();
    }
    
    // ---------------------------------------------------------
    // Process item search
    // ---------------------------------------------------------
    function process_search()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $SID;
        
        $triggers_array = array();
        if ( !empty($_POST['query']) )
        {
            $eqdkp_triggers      = array();
            $eqdkp_trigger_stats = array();
            
            //
            // Get trigger names from our standard triggers table
            //
            $sql = 'SELECT trigger_name
                    FROM ' . TRIGGERS_TABLE . "
                    WHERE trigger_name LIKE '%" . $_POST['query'] . "%'
                    ORDER BY trigger_name";
            $result = $db->query($sql);
            while ( $row = $db->fetch_record($result) )
            {
                $eqdkp_triggers[] = $row['trigger_name'];
            }
            $db->free_result($result);
            
            //
            // Get item names from our stats table if the stats plugin is installed
            //

            // #######################################
            // Alteration sumbitted by Tam
            // #######################################
            if ( $pm->check(PLUGIN_INSTALLED, 'stats') )
                  {
                      $sql = 'SELECT name
                              FROM ' . ITEM_STATS_TABLE . "
                              WHERE name LIKE '%" . $_POST['query'] . "%'
                              ORDER BY name";
                      $result = $db->query($sql);
                      while ( $row = $db->fetch_record($result) )
                      {
                          // Add the item if we don't have it already
                          if ( !in_array($row['item_name'], $eqdkp_items) )
                          {
                              $eqdkp_item_stats[] = $row['name'];
                          }
                      }
                      $db->free_result($result);
                  }
            //#######################################

            //
            // Build the drop-down
            //
            $triggers_array = array_merge($eqdkp_triggers, $eqdkp_trigger_stats);
            $triggers_array = array_unique($triggers_array);
            sort($triggers_array);
            reset($triggers_array);
            
            foreach ( $triggers_array as $trigger_name )
            {
                $tpl->assign_block_vars('triggers_row', array(
                    'VALUE'  => stripslashes($trigger_name),
                    'OPTION' => stripslashes($trigger_name))
                );
            }
        }
        
        $tpl->assign_vars(array(
            'S_STEP1' => false,
            
            'L_RESULTS' => sprintf($user->lang['results'], sizeof($triggers_array), stripslashes($_POST['query'])),
            'L_SELECT'  => $user->lang['select'])
        );
        
        $eqdkp->set_vars(array(
            'page_title'        => sprintf($user->lang['admin_title_prefix'], $eqdkp->config['guildtag'], $eqdkp->config['dkp_name']).': '.$user->lang['addtrigger_title'],
            'gen_simple_header' => true,
            'template_file'     => 'admin/addtrigger_search.html',
            'display'           => true)
        );
    }
    
    // ---------------------------------------------------------
    // Display item search
    // ---------------------------------------------------------
    function display_form()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $SID;
        
        $tpl->assign_vars(array(
            'F_SEARCH_TRIGGERS' => 'addtrigger.php' . $SID . '&amp;mode=search',
            'S_STEP1'       => true,
            'ONLOAD'        => ' onload="javascript:document.post.query.focus()"',
            
            'L_TRIGGER_SEARCH'  => $user->lang['trigger_search'],
            'L_SEARCH'       => $user->lang['search'],
            'L_CLOSE_WINDOW' => $user->lang['close_window'])
        );
        
        $eqdkp->set_vars(array(
            'page_title'        => sprintf($user->lang['admin_title_prefix'], $eqdkp->config['guildtag'], $eqdkp->config['dkp_name']).': '.$user->lang['addtrigger_title'],
            'gen_simple_header' => true,
            'template_file'     => 'admin/addtrigger_search.html',
            'display'           => true)
        );
    }
}

$mode = ( isset($_GET['mode']) ) ? $_GET['mode'] : 'addtrigger';
switch ( $mode )
{
    case 'addtrigger':
        $add_trigger = new Add_Trigger;
        $add_trigger->process();
        break;
    
    case 'search':
        $trigger_search = new Trigger_Search;
        $trigger_search->process();
        break;
}
?>
